Skip to content

MeanMetricWrapper metric

Bases: Mean

Average a per-sample function as a metric; for stateless custom metrics.

You could use this class to quickly build a mean metric from a function. The function needs to have the signature fn(y_true, y_pred) and return a per-sample reward array. MeanMetricWrapper.result() will return the average metric value across all samples seen so far.

Example:

program.compile(
    metrics=[
        synalinks.metrics.MeanMetricWrapper(
            synalinks.rewards.exact_match,
            in_mask=["answer"],
        ),
    ],
)

Parameters:

Name Type Description Default
fn callable

The metric function to wrap, with signature fn(y_true, y_pred, **kwargs).

required
name str

(Optional) string name of the metric instance.

None
in_mask list

(Optional) list of keys to keep to compute the metric.

None
out_mask list

(Optional) list of keys to remove to compute the metric.

None
in_mask_pattern str

(Optional) Regex pattern; fields whose names match are kept (combined with in_mask via OR).

None
out_mask_pattern str

(Optional) Regex pattern; fields whose names match are dropped (combined with out_mask via OR).

None
**kwargs keyword arguments

Keyword arguments to pass on to fn.

{}
Source code in synalinks/src/metrics/reduction_metrics.py
@synalinks_export("synalinks.metrics.MeanMetricWrapper")
class MeanMetricWrapper(Mean):
    """Average a per-sample function as a metric; for stateless custom metrics.

    You could use this class to quickly build a mean metric from a function. The
    function needs to have the signature `fn(y_true, y_pred)` and return a
    per-sample reward array. `MeanMetricWrapper.result()` will return
    the average metric value across all samples seen so far.


    Example:

    ```python
    program.compile(
        metrics=[
            synalinks.metrics.MeanMetricWrapper(
                synalinks.rewards.exact_match,
                in_mask=["answer"],
            ),
        ],
    )
    ```

    Args:
        fn (callable): The metric function to wrap, with signature
            `fn(y_true, y_pred, **kwargs)`.
        name (str): (Optional) string name of the metric instance.
        in_mask (list): (Optional) list of keys to keep to compute the metric.
        out_mask (list): (Optional) list of keys to remove to compute the metric.
        in_mask_pattern (str): (Optional) Regex pattern; fields whose names match
            are kept (combined with ``in_mask`` via OR).
        out_mask_pattern (str): (Optional) Regex pattern; fields whose names match
            are dropped (combined with ``out_mask`` via OR).
        **kwargs (keyword arguments): Keyword arguments to pass on to `fn`.
    """

    def __init__(
        self,
        fn,
        name=None,
        description=None,
        in_mask=None,
        out_mask=None,
        in_mask_pattern=None,
        out_mask_pattern=None,
        **kwargs,
    ):
        super().__init__(
            name=name,
            in_mask=in_mask,
            out_mask=out_mask,
            in_mask_pattern=in_mask_pattern,
            out_mask_pattern=out_mask_pattern,
            description=description,
        )
        self._fn = fn
        self._fn_kwargs = kwargs
        if description is None and type(self) is MeanMetricWrapper:
            self.description = docstring_summary(fn)

    async def update_state(self, y_true, y_pred, x=None):
        masks = {
            "in_mask": self.in_mask,
            "in_mask_pattern": self.in_mask_pattern,
            "out_mask": self.out_mask,
            "out_mask_pattern": self.out_mask_pattern,
        }
        y_true, y_pred = apply_masks(y_true, y_pred, **masks)
        kwargs = dict(self._fn_kwargs)
        if accepts_argument(self._fn, "x"):
            kwargs["x"] = mask_data_models(x)  # Masks select y_true/y_pred fields.
        values = await self._fn(y_true, y_pred, **kwargs)
        # No grade counts as 0.0 (as for rewards), not as a NaN sample.
        return await super().update_state(0.0 if values is None else values)

    async def close(self):
        """Close the reward this metric wraps (a judge's program). Idempotent."""
        closer = getattr(self._fn, "close", None)
        if closer is not None and inspect.iscoroutinefunction(closer):
            await closer()

    def get_config(self):
        """Returns the serializable config of the metric."""
        base_config = super().get_config()
        config = {
            "fn": serialization_lib.serialize_synalinks_object(self._fn),
        }
        config.update(self._fn_kwargs)
        return {**base_config, **config}

    @classmethod
    def from_config(cls, config):
        fn = serialization_lib.deserialize_synalinks_object(config.pop("fn"))
        return cls(fn=fn, **config)

close() async

Close the reward this metric wraps (a judge's program). Idempotent.

Source code in synalinks/src/metrics/reduction_metrics.py
async def close(self):
    """Close the reward this metric wraps (a judge's program). Idempotent."""
    closer = getattr(self._fn, "close", None)
    if closer is not None and inspect.iscoroutinefunction(closer):
        await closer()

get_config()

Returns the serializable config of the metric.

Source code in synalinks/src/metrics/reduction_metrics.py
def get_config(self):
    """Returns the serializable config of the metric."""
    base_config = super().get_config()
    config = {
        "fn": serialization_lib.serialize_synalinks_object(self._fn),
    }
    config.update(self._fn_kwargs)
    return {**base_config, **config}